package com.friverosy.pds.clientesoap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.nicolascarrascob.clientesoap.R;

public class UpdatePeliculaActivity extends Activity{

	private String URL = Constantes.HOST + "/ServicioWebSoap/services/CarteleraCineORMWS";
	private String NAMESPACE = "http://ws.serviciosoap.pds.nicolascarrascob.com";

	Pelicula pelicula;
	ArrayList<String> generos;
	ArrayList<String> clasificaciones;
	Spinner generosSpinner;
	Spinner clasificacionesSpinner;
	EditText nombreEditText;
	EditText descripcionEditText;
	CheckBox estrenoCheckbox;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_updatepelicula);
		generosSpinner = (Spinner) findViewById(R.id.addpelicula_genero);
		clasificacionesSpinner = (Spinner) findViewById(R.id.addpelicula_planificacion);
		nombreEditText = (EditText) findViewById(R.id.addpelicula_nombre);
		descripcionEditText = (EditText) findViewById(R.id.addpelicula_descripcion);
		estrenoCheckbox = (CheckBox) findViewById(R.id.addpelicula_estreno);
		generos = new ArrayList<String>();
		clasificaciones = new ArrayList<String>();
		new ObtenerGenerosClasificacionBackground().execute();
	}

	public void guardar(View v){
		JsonObject jsonObjectPelicula = new JsonObject();
		//		jsonObjectPelicula.addProperty("nombre", "peli");
		//		jsonObjectPelicula.addProperty("descripcion", "peliculaaaas");
		//		jsonObjectPelicula.addProperty("estreno", 1);
		//		jsonObjectPelicula.addProperty("genero_id", "1");
		//		jsonObjectPelicula.addProperty("clasificacion_id", "1");

		jsonObjectPelicula.addProperty("id", pelicula.getId());
		jsonObjectPelicula.addProperty("nombre", nombreEditText.getText().toString());
		jsonObjectPelicula.addProperty("descripcion", descripcionEditText.getText().toString());
		jsonObjectPelicula.addProperty("estreno", estrenoCheckbox.isChecked() ? 1 : 0);
		jsonObjectPelicula.addProperty("genero_id", generos.get(generosSpinner.getSelectedItemPosition()));
		jsonObjectPelicula.addProperty("clasificacion_id", clasificaciones.get(clasificacionesSpinner.getSelectedItemPosition()));
		Log.d("",jsonObjectPelicula.toString());
		new UpdatePeliculaBackground().execute(jsonObjectPelicula.toString());
	}
	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_updatepelicula, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.remove_pelicula:
            	Log.d("",pelicula.getId());
            	new RemovePeliculaBackground().execute(Integer.parseInt(pelicula.getId()));
            	return true;
            default:
                return true;
        }
    }

	class ObtenerGenerosClasificacionBackground extends AsyncTask<Void, Void, HashMap<String, String>>{

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(
					UpdatePeliculaActivity.this,
					"Cartelera de Cine", 
					"Espere mientras se carga la cartelera...", 
					true);
			super.onPreExecute();
		}

		@Override
		protected HashMap<String, String> doInBackground(Void... params) {

			HashMap<String, String> resultado = new HashMap<String, String>();
			String generosJSON="";
			String METHOD_NAME = "getGeneros";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				generosJSON = resultString.toString();
				resultado.put("generos", generosJSON);

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			String clasificacionesJSON="";
			METHOD_NAME = "getClasificaciones";
			SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			request = new SoapObject(NAMESPACE, METHOD_NAME);
			soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes =true;
			soapEnvelope.setOutputSoapObject(request);

			aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				clasificacionesJSON = resultString.toString();
				resultado.put("clasificaciones", clasificacionesJSON);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
			return resultado;
		}

		@Override
		protected void onPostExecute(HashMap<String, String> result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			pelicula = (Pelicula) getIntent().getExtras().getSerializable("pelicula");
			Log.d("", pelicula.toString());
			nombreEditText.setText(pelicula.getTitulo());
			descripcionEditText.setText(pelicula.getDescripcion());
			estrenoCheckbox.setChecked("Si".equals(pelicula.getEstreno()));
			//Valido que tenga la informacion necesaria
			if(result.containsKey("generos") && !"".equals(result.get("generos"))){
				try {
					ArrayList<String> generosList = new ArrayList<String>();
					JSONObject generoResultado = new JSONObject(result.get("generos"));
					String contenido = generoResultado.getString("Contenido");
					JSONObject peliculasJSONArray = new JSONObject(contenido);
					peliculasJSONArray.names();
					peliculasJSONArray.keys();
					for (Iterator iterator = peliculasJSONArray.keys(); iterator.hasNext();) {
						String string = (String) iterator.next();
						generos.add(string);
						generosList.add(peliculasJSONArray.getString(string));
					}

					ArrayAdapter<String> generosAdapter = new ArrayAdapter<String>(UpdatePeliculaActivity.this, android.R.layout.simple_spinner_item, generosList);
					generosSpinner.setAdapter(generosAdapter);

					for(String genero : generosList){
						if(genero.equals(pelicula.getGenero())){
							Log.d("", generosList.indexOf(genero)+"");
							generosSpinner.setSelection(generosList.indexOf(genero));
						}
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				Toast.makeText(UpdatePeliculaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}

			if(result.containsKey("clasificaciones") && !"".equals(result.get("clasificaciones"))){
				try {
					ArrayList<String> clasificacionesList = new ArrayList<String>();
					JSONObject generoResultado = new JSONObject(result.get("clasificaciones"));
					String contenido = generoResultado.getString("Contenido");
					JSONObject peliculasJSONArray = new JSONObject(contenido);
					peliculasJSONArray.names();
					peliculasJSONArray.keys();
					for (Iterator iterator = peliculasJSONArray.keys(); iterator.hasNext();) {
						String string = (String) iterator.next();
						clasificaciones.add(string);
						clasificacionesList.add(peliculasJSONArray.getString(string));
					}

					ArrayAdapter<String> clasificacionesAdapter = new ArrayAdapter<String>(UpdatePeliculaActivity.this, android.R.layout.simple_spinner_item, clasificacionesList);
					clasificacionesSpinner.setAdapter(clasificacionesAdapter);

					for(String clasificacion : clasificacionesList){
						Log.d("", clasificacion + " vs " + pelicula.getClasificacion());
						if(clasificacion.equals(pelicula.getClasificacion())){
							Log.d("", clasificacionesList.indexOf(clasificacion)+"");
							clasificacionesSpinner.setSelection(clasificacionesList.indexOf(clasificacion));
						}
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}else{
				Toast.makeText(UpdatePeliculaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}

	class UpdatePeliculaBackground extends AsyncTask<String, Void, String>{

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(
					UpdatePeliculaActivity.this,
					"Cartelera de Cine", 
					"Espere mientras se actualizando la pelicula...", 
					true);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {

			String resultado = new String();
			String METHOD_NAME = "updatePelicula";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("jsonPelicula", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if("1".equals(result)){
				Toast.makeText(UpdatePeliculaActivity.this, "Ingresada correctamente", Toast.LENGTH_LONG).show();
				finish();
			}else{
				Toast.makeText(UpdatePeliculaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}

	class RemovePeliculaBackground extends AsyncTask<Integer, Void, String>{

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(
					UpdatePeliculaActivity.this,
					"Cartelera de Cine", 
					"Espere mientras se elimina la pelicula...", 
					true);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Integer... params) {

			String resultado = new String();
			String METHOD_NAME = "removePelicula";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("peliculaId", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if("1".equals(result)){
				Toast.makeText(UpdatePeliculaActivity.this, "Eliminada correctamente", Toast.LENGTH_LONG).show();
				finish();
			}else{
				Toast.makeText(UpdatePeliculaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}


}
